package pub.wkq.auth.service.impl;

import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import pub.wkq.api.feign.WorkMicroServiceFeign;
import pub.wkq.api.mq.InitResumeMQConfig;
import pub.wkq.auth.mapper.UsersMapper;
import pub.wkq.auth.mq.InitResumeMQProducerHandler;
import pub.wkq.auth.service.UsersService;
import pub.wkq.common.exception.CustomException;
import pub.wkq.common.result.JSONResult;
import pub.wkq.common.result.ResponseStatusEnum;
import pub.wkq.common.utils.SerializationUtils;
import pub.wkq.pojo.Users;

import javax.annotation.Resource;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author 王开琦
 * @since 2023-06-05
 */
@Service
@Slf4j
public class UsersServiceImpl implements UsersService {
    @Resource
    private UsersMapper usersMapper;
    @Resource
    private WorkMicroServiceFeign workMicroServiceFeign;

    @Resource
    private RabbitTemplate rabbitTemplate;

    @Resource
    private InitResumeMQProducerHandler initResumeMQProducerHandler;

    @Override
    public Users queryUserIsExist(String mobile) {
        //mobile是唯一索引，所以可以用这个方法
        return new LambdaQueryChainWrapper<>(usersMapper).eq(Users::getMobile, mobile).one();
    }

    @Override
    @Transactional
//    @GlobalTransactional
    public Users createUser(String mobile) {
        Users users = Users.initUser(mobile);
        usersMapper.insert(users);
        //发起远程调用，初始化用户简历
//        JSONResult jsonResult = workMicroServiceFeign.initResume(users.getId());
//        if (!jsonResult.getSuccess()) {
//            //如果调用状态不是 200 ，则回滚全局事务
//            throw new CustomException(ResponseStatusEnum.RESUME_INIT_ERROR);
//        }
//        int a = 1 / 0; // 测试分布式事务
        return users;
    }

    @Override
    @Transactional
    public Users createUserAndInitResumeMQ(String mobile) {
        //创建用户
        Users user = createUser(mobile);
        //本地消息存储
        initResumeMQProducerHandler.saveLocalMsgRecord(InitResumeMQConfig.INIT_RESUME_EXCHANGE, InitResumeMQConfig.INIT_RESUME_ROUTING_KEY, SerializationUtils.serializeObject(user.getId()));
//        发送消息初始化简历
        rabbitTemplate.convertAndSend(InitResumeMQConfig.INIT_RESUME_EXCHANGE, InitResumeMQConfig.INIT_RESUME_ROUTING_KEY, SerializationUtils.serializeObject(user.getId()));
        return user;
    }
}
